<template>
  <div class="upload">
    <div class="top-header border-bottom fixed-top">
      <div class="top-back">
        <a href="javascript:void(0)" @click="back">返回</a>
      </div>
      <h2 class="f36 color-000">{{$route.query.gameName || ''}}</h2>
    </div>
    <div style="height: .97rem; width: 100%"></div>
    <!--风控警告提示 mt-97  -->
      
    <FkRemind class="mt-97"></FkRemind>
    <div v-if="!list ||list.length <= 0">
      <div class="order-container px-30 mt-79 bg-fff border-bottom">
        <span class="f32 color-000 new-tip">图片上传的越全，帐号卖的越快</span>
      </div>
      <div class="bg-fff new-upload-img p-30 border-bottom">
        <div class="">
          <label>
            <input type="file" name="imageFile" class="upload" @change="fileChange" :accept="accepts"
                   :multiple="true">
          </label>
          <p class="f32 color-000 text-center">上传图片</p>
        </div>
      </div>
      <p class="px-30 py-20 f24 color-666">注：单次最多可选15张</p>
    </div>
    <div class="progress" v-if="supportProgress && percent > 0">
      <span :style="{width:percent+'%'}"></span>
      <em class="pa">{{percent}}%</em>
    </div>
    <div class="upload-img-list bg-fff px-30 pt-30 mt-79 clearfix" v-if="list && list.length > 0">
      <div class="fl mb-30 img-list-item" v-for="(path,index) in list" :key="path.imgId">
        <img :src="path.small_pic">
        <i class="del-img" @click="deleteImg(index, path)"></i>
      </div>
      <div class="fl mb-30 add-img">
        <label>
          <input type="file" name="imageFile" class="upload" @change="fileChange" :accept="accepts"
                 :multiple="true">
        </label>
        <p class="f26 mt-10 color-000 text-center">上传图片</p>
      </div>
    </div>
    <div class="contaner-qq fw border-bottom" v-if="showHint && this.list.length === 0"><p class="f24">请上传图片</p></div>
    <!-- 下一步 -->
    <div class="release mt-20 trlect-btn border">
      <a class="next" href="JavaScript:void(0)" @click="confirm">
        <input class="bg-f54" type="button" name="" value="下一步">
      </a>
    </div>
  </div>
</template>

<script>
 import FkRemind from 'components/common/FkRemind';
  export default {
    props: {
      // 编辑初始化图片
      initImages: {
        type: Array
      }
    },
    data() {
      return {
        showHint: false,
        list: [], // 图片列表
        accepts: "", // 放入input中的属性值
        ext: 'jpg,png', // 允许上传的图片类型
        mimes: { // 类型对应列表
          "jpg": "image/jpeg",
          "png": "image/png",
          "gif": "image/gif"
        },
        limit: 3 * 1024 * 1024, // 图片大小限制
        files: [], // 文件列表
        supportProgress: false,
        percent: 0 ,// 上传进度
        icon:'icon_down fr',//新增防骗提醒样式
        icon1:'icon1_style',
        icons: 1,
      }
    },
    components:{
      FkRemind,
    },
    watch: {
      initImages(val) {
        this.list.push(...val)
      },
      percent(val) {
        if (this.percent == 100) {
          setTimeout(() => {
            this.percent = 0
          }, 500)
        }
      },
    },
    created() {
      let accepts = []
      let exts = this.ext.split(",");
      for (let i = 0; i < exts.length; i++) {
        accepts.push(this.mimes[exts[i]]);
      }
      this.accepts = accepts.join(",");
    },
    methods: {
       // 防骗提醒
      warning:  function () {
        if (this.icons == 1) {
           this.icon = 'icon_up fr'
          this.icon1 = 'f24  fl';
         this.icons++;
        }else{
          this.icon ='icon_down fr '
          this.icon1 ='icon1_style '
          this.icons = 1;
        }
      },
      back() {
        this.$emit('imageUploadBack')
      },
      /* 点击下一步 */
      confirm() {
        /* 校验是否无图 */
        this.showHint = true
        if(!this.list.length) return
        this.$emit('imageUploadConfirm', this.list.map(path => {
          return {
            thumbnailsUrl: path.small_pic,
            originalUrl: path.big_pic
          }
        }))
      },
      fileChange(e) { // 本地上传文件到浏览器
        this.input = e.target
        this.files = this.getFiles(e)
        if(this.files.length + this.list.length > 15) {
          this.$toast('图片上传最多15张')
          this.files = []
          return
        }
        this.uploadFiles()
      },
      /* 筛选后获取上传到浏览器的文件列表 */
      getFiles(e) {
        e.stopPropagation();
        e.preventDefault();
        let files = _turn(e.target.files)
        let _exts = this.ext.split(",")
        let _mimes = []
        if (_exts.length > 0) {
          _exts.forEach(v => {
            if (this.mimes[v] !== undefined) {
              _mimes.push(this.mimes[v])
            }
          })
        }
        files = files.filter(file => {
          if (file.size > this.limit || !_mimes.indexOf(JSON.stringify(file.type))) {
            this.$toast('请上传正确格式的图片，或大小不能超过3MB');
            return false
          }
          return true
        })

        function _turn(files) {
          let newFiles = []
          for (let i = 0, file; file = files[i]; i++) {
            newFiles.push(file)
          }
          return newFiles
        }

        return files
      },
      /* 上传文件到服务器 */
      uploadFiles() {
        if (this.files.length === 0) return false;
        let loadedAll = []
        let totalAll = []
        /* 一个是数据上传的比例，另一个是响应的个数  相加为100 */
        let dataPercent = 0
        let numberPercent = 0
        this.files.forEach((file, index) => {
          let formData = new FormData();
          formData.append('file', file)
          this.$http.post(this.$CONSTANTS.APIMGCoin +'upload/uploadImage', formData, {
            progress: (event) => {
              // 标记是否支持progress监听事件，iphone Uc、QQ等，不支持该监听
              if (!this.supportProgress) this.supportProgress = true
              loadedAll[index] = event.loaded
              totalAll[index] = event.total
              dataPercent = Math.floor(_sum(loadedAll) / _sum(totalAll) * (100 - this.files.length))
              if (this.percent !== 100) { // 躲异常异步
                this.percent = dataPercent + numberPercent
              }
            }
          }).then(res => {
            if (res.body.success) {
              numberPercent++
              if (this.percent !== 100) { // 躲异常异步
                this.percent = dataPercent + numberPercent
              }
              let path = res.body.data
              this.list.push(path)
            } else {
              _showError.call(this, file)
            }
          }, err => {
            _showError.call(this, file)
          })
        })
        function _showError(file) {
          this.$toast({
            message: `服务器异常! '${file.name}'上失败`,
            position: 'bottom'
          });
          numberPercent++
          if (this.percent !== 100) { // 躲异常异步
            this.percent = dataPercent + numberPercent
          }
        }
        function _sum(arr) {
          return arr.reduce((v1, v2) => v1 + v2)
        }
      },
      /* 删除图片链接 */
      deleteImg(index) {
        if (!this.list.length) {
          this.$toast('请先上传图片');
        }else{
          // this.$http.get('/api/mobile-fullauto-service/rs/upload/delImgAli', {params: {imageUrl}}).then(res => {
            this.list.splice(index, 1);
          // })
        }
      }
    }
  }
</script>
<style scoped>
  .upload {
    position: relative;
    width: 100%;
    height: 100%;
    cursor: pointer;
    border-radius: inherit;
  }

  .upload .image {
    transition: all .3s ease-in-out;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: inherit;
  }

  .upload > input {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    opacity: 0;
    cursor: pointer;
  }

  .upload .progress {
    position: fixed;
    left: 0;
    bottom: 0;
    right: 0;
    top: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, .8);
    z-index: 99;
  }

  .upload .progress span {
    box-sizing: border-box;
    display: block;
    height: 100%;
    width: 0%;
    border-bottom: 5px solid rgba(164, 208, 99, .8);
  }

  .upload .progress em {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: .8rem;
    line-height: 100%;
    color: #fff;
  }
   /* 风控警告提示 */
.Mnotice_top{position:absolute;top:0rem;width: 100%;}
.mt-79{margin-top: 0.78rem}
.icon1_style{display: none}
.Mmt-175{margin-top: 1.75rem}
.notice_risk{height: auto;display: block;overflow: hidden;background-color: #fffdf4;}
.notice_risk .icon_notice{background: url('~images/seller/notice_no.png') center center no-repeat;width:.3rem;height:.78rem;line-height:.78rem;background-size:.3rem;display:inline-block;margin-right:.1rem;} 
.notice_risk .notice_wz{line-height: .38rem;padding: .2rem 0rem .2rem 0rem;color: #be8600;} 
.notice_risk .notice_public{padding:.2rem 0 .2rem 0;width:95%;}
.notice_risk .notice_public p{height:.35rem;line-height:.35rem;color: #be8600;overflow:hidden;}
.notice_risk .icon_down{background: url('~images/seller/icon_down.png') center center no-repeat;width:.24rem;height:.75rem;line-height:.75rem;background-size:.24rem;display:inline-block;float:right;}
.notice_risk .icon_up{background: url('~images/seller/icon_up.png') center center no-repeat ;width:.24rem;height:.75rem;line-height:.75rem;background-size:.24rem;display:inline-block;float:right;}  

  
</style>
